import { mapState } from 'vuex'
import timCard from '@/components/commen/timCard.vue'

export default {
  data() {
    return {
      //TIM变量
      nextReqMessageID: '',
      count: 15,
      isCompleted: '',
      msgList: [],
      TIM: null,

      //文字消息
      textMsg: '',
      //消息列表
      isHistoryLoading: false,
      scrollAnimation: false,
      scrollTop: 0,
      scrollToView: '',

      msgImgList: [],
      myuid: 0,
      fileCopy: [],

      //录音相关参数
      // #ifndef H5
      //H5不能录音
      RECORDER: uni.getRecorderManager(),
      // #endif
      isVoice: false,
      voiceTis: '按住 说话',
      recordTis: '手指上滑 取消发送',
      recording: false,
      willStop: false,
      initPoint: {
        identifier: 0,
        Y: 0,
      },
      recordTimer: null,
      recordLength: 0,

      //播放语音相关参数
      AUDIO: uni.createInnerAudioContext(),
      playMsgid: null,
      VoiceTimer: null,
      isPlay: false,
      // 抽屉参数
      popupLayerClass: '',
      // more参数
      hideMore: true,
      //表情定义
      hideEmoji: true,
      emojiList: this.$commen.emojiList,
      //红包相关参数
      windowsState: '',
      redenvelopeData: {
        rid: null, //红包ID
        from: null,
        face: null,
        blessing: null,
        money: null,
      },
      isAddFlow: false, //是否添加聊天记录，仅添加一次
    }
  },
  computed: {
    ...mapState({
      currentMessageList: (state) => state.news.currentMessageList,
      toUserInfo: (state) => state.news.toUserInfo,
    }),
    userInfo() {
      return {
        img: this.$store.state.news.img,
        user: this.$store.state.news.user,
        userId: this.$store.state.news.userId,
        userSig: this.$store.state.news.userSig,
      }
    },
    toUserId() {
      return this.$store.state.news.toUserId
    },
    conversationActive() {
      return this.$store.state.news.conversationActive
    },
  },
  watch: {
    currentMessageList(newVal, oldVal) {
      if (newVal.length) {
        this.msgList = newVal
      }
      this.screenMsg(newVal, oldVal)
    },
  },
  components: {
    timCard,
  },
  onLoad(option) {
    // 头部标题
    if (option.user && option.user !== 'null' && option.user !== 'undefined') {
      uni.setNavigationBarTitle({
        title: option.user,
      })
    } else {
      uni.setNavigationBarTitle({
        title: '聊天',
      })
    }
    this.TIM = this.$TIM
    //获取聊天对象的用户信息
    // userList.forEach(item=>{
    // 	// debugger
    // 	if(this.toUserId == item.userId){
    // debugger
    // 	}
    // })
    this.getMsgList()
    //语音自然播放结束
    this.AUDIO.onEnded((res) => {
      this.playMsgid = null
    })
    // #ifndef H5
    //录音开始事件
    this.RECORDER.onStart((e) => {
      this.recordBegin(e)
    })
    //录音结束事件
    this.RECORDER.onStop((e) => {
      this.recordEnd(e)
    })
    // #endif
  },
  onShow() {
    this.scrollTop = 9999999
  },
  onUnload() {
    //退出页面 将所有的会话内的消息设置为已读
    let promise = this.tim.setMessageRead({
      conversationID: this.conversationActive.conversationID,
    })
    promise
      .then(function (imResponse) {
        console.log('全部已读')
        // 已读上报成功
      })
      .catch(function (imError) {
        // 已读上报失败
        console.warn('setMessageRead error:', imError)
      })
  },
  methods: {
    clickFn(e, flag) {
      const data = JSON.parse(e)
      let url
      if (data.customMsgType === 'carSource') {
        //车源
        url =
          '/pages_carSource/productDetail/productDetail?pageFrom=chat&goodsid=' +
          data.id
      } else if (data.customMsgType === 'orderInfo') {
        //订单
        if (flag) {
          data.tab = data.tab === '1' ? '0' : '1'
        }
        url =
          '/pages_order/carOrderDetail/carOrderDetail?pageFrom=chat&id=' +
          data.id +
          '&tab=' +
          data.tab
      } else if (data.customMsgType === 'accessory') {
        //寻配件
        if (flag) {
          //对方发出的链接
          data.tab = data.tab === '1' ? '0' : '1'
        }
        if (data.tab === '1') {
          //进入报价
          url =
            '/pages_findAccessory/myQuoteDetail/myQuoteDetail?pageFrom=chat&id=' +
            data.id
        } else {
          //进入询价
          url =
            '/pages_findAccessory/myInquiryDetail/myInquiryDetail?pageFrom=chat&id=' +
            data.id
        }
      } else if (data.customMsgType === 'accessoryOrder') {
        //寻配件 我的报价订单、我的询价订单
        if (flag) {
          //对方发出的链接
          data.tab = data.tab === '1' ? '0' : '1'
        }
        if (data.tab === '1') {
          //进入报价订单
          url =
            '/pages_order/accessoryOrder/quoteOrderDetail/quoteOrderDetail?pageFrom=chat&id=' +
            data.id
        } else {
          //进入询价订单
          url =
            '/pages_order/accessoryOrder/inquiryOrderDetail/inquiryOrderDetail?pageFrom=chat&id=' +
            data.id
        }
      } else if (data.customMsgType === 'findCar') {
        //寻车
        if (flag) {
          //对方发出的链接
          data.tab = data.tab === '1' ? '0' : '1'
        }
        if (data.tab === '1') {
          //进入报价订单
          url =
            '/pages_findCar/hasQuotedForTheCar/hasQuotedForTheCar?pageFrom=chat&goodsid=' +
            data.id
        } else {
          //进入询价订单
          url =
            '/pages_findCar/detailsOfMyOffer/detailsOfMyOffer?pageFrom=chat&id=' +
            data.id
        }
      } else if (data.customMsgType === 'carGoods') {
        //车品
        if (flag) {
          //对方发出的链接
          data.tab = data.tab === '1' ? '0' : '1'
        }
        if (data.tab === '1') {
          //进入我的购买订单详情
          url =
            '/pages_order/carGoodsOrder/buyOrderDetail/buyOrderDetail?pageFrom=chat&id=' +
            data.id
        } else {
          //进入我的销售订单详情
          url =
            '/pages_order/carGoodsOrder/salesOrderDetail/salesOrderDetail?pageFrom=chat&id=' +
            data.id
        }
      } else if (data.customMsgType === 'resaleCar') {
        //寻车-零售订单
        url =
          '/pages_order/retailOrderDetail/retailOrder?pageFrom=chat&id=' +
          data.id +
          '&oneTab=' +
          data.tab
      } else if (data.customMsgType === 'afterSales') {
        //维保订单
        url =
          '/pages_afterSales/order/orderDetail/orderDetail?pageFrom=chat&id=' +
          data.id
      }
      uni.navigateTo({
        url: url,
      })
    },
    //聊天的节点加上外层的div
    nodesFliter(str) {
      let nodeStr =
        '<div style="align-items: center;word-wrap:break-word;">' +
        str +
        '</div>'
      return nodeStr
    },
    //时间过滤
    timeFliter(timer) {
      let timeData = new Date(timer * 1000)
      let str = this.$commen.dateTimeFliter(timeData)
      return str
    },
    // 接受消息(定位消息)
    screenMsg(newVal, oldVal) {
      if (newVal.length == 0) {
        return false
      } else if (oldVal.length == 0) {
        this.$nextTick(() => {
          this.scrollToView = newVal[newVal.length - 1].ID
        })
      } else {
        if (newVal[0].ID && oldVal[0].ID) {
          if (newVal[0].ID != oldVal[0].ID && newVal.length >= this.count) {
            this.$nextTick(() => {
              this.scrollToView = oldVal[0].ID
            })
          } else {
            this.$nextTick(() => {
              this.scrollToView = newVal[newVal.length - 1].ID
            })
          }
        } else {
          this.$nextTick(() => {
            this.scrollToView = newVal[newVal.length - 1].ID
          })
        }
      }
    },
    //触发滑动到顶部(加载历史信息记录)
    loadHistory(e) {
      // 更多消息列表
      let conversationID = this.conversationActive.conversationID
      console.log(this.nextReqMessageID)
      let promise = this.tim.getMessageList({
        conversationID: conversationID,
        nextReqMessageID: this.nextReqMessageID,
        count: this.count,
      })
      promise.then((res) => {
        if (res.data.messageList.length) {
          this.$store.commit(
            'news/unshiftCurrentMessageList',
            res.data.messageList
          )
          this.nextReqMessageID = res.data.nextReqMessageID // 用于续拉，分页续拉时需传入该字段。
          this.isCompleted = res.data.isCompleted
        }
        console.log(res)
      })
      //这段代码很重要，不然每次加载历史数据都会跳到顶部
      this.$nextTick(function () {
        console.log(this.nextReqMessageID)
        this.scrollToView = this.nextReqMessageID //跳转上次的第一行信息位置
        this.$nextTick(function () {
          this.scrollAnimation = true //恢复滚动动画
        })
      })
      this.isHistoryLoading = false
    },
    // 加载初始页面消息
    getMsgList() {
      // 历史消息列表
      let conversationID = this.conversationActive.conversationID
      let promise = this.tim.getMessageList({
        conversationID: conversationID,
        count: this.count,
      })
      if (promise == undefined) {
        return false
      } else {
        promise.then((res) => {
          this.$store.commit(
            'news/pushCurrentMessageList',
            res.data.messageList
          )
          if (
            res.data.messageList == '' ||
            res.data.messageList == undefined ||
            res.data.messageList.length == 0
          ) {
            return false
          } else {
            this.nextReqMessageID = res.data.nextReqMessageID // 用于续拉，分页续拉时需传入该字段。
            this.isCompleted = res.data.isCompleted
            this.$nextTick(() => {
              this.scrollToView =
                res.data.messageList[res.data.messageList.length - 1].ID
            })
          }
        })
      }
      // 滚动到底部
      this.$nextTick(function () {
        //进入页面滚动到底部
        this.scrollTop = 9999
        this.$nextTick(function () {
          this.scrollAnimation = true
        })
      })
    },
    //处理图片尺寸，如果不处理宽高，新进入页面加载图片时候会闪
    setPicSize(content) {
      // 让图片最长边等于设置的最大长度，短边等比例缩小，图片控件真实改变，区别于aspectFit方式。
      let maxW = uni.upx2px(350) //350是定义消息图片最大宽度
      let maxH = uni.upx2px(350) //350是定义消息图片最大高度
      if (content.w > maxW || content.h > maxH) {
        let scale = content.w / content.h
        content.w = scale > 1 ? maxW : maxH * scale
        content.h = scale > 1 ? maxW / scale : maxH
      }
      return content
    },
    //更多功能(点击+弹出)
    showMore() {
      this.isVoice = false
      this.hideEmoji = true
      if (this.hideMore) {
        this.hideMore = false
        this.openDrawer()
      } else {
        this.hideDrawer()
      }
    },
    // 打开抽屉
    openDrawer() {
      this.popupLayerClass = 'showLayer'
    },
    // 隐藏抽屉
    hideDrawer() {
      this.popupLayerClass = ''
      setTimeout(() => {
        this.hideMore = true
        this.hideEmoji = true
      }, 150)
    },
    // 选择图片发送
    chooseImage() {
      this.uploadImage('album')
    },
    //拍照发送
    camera() {
      this.uploadImage('camera')
    },
    //发红包
    handRedEnvelopes() {
      uni.navigateTo({
        url: 'HM-hand/HM-hand',
      })
      this.hideDrawer()
    },

    // 选择表情
    chooseEmoji() {
      this.hideMore = true
      if (this.hideEmoji) {
        this.hideEmoji = false
        this.openDrawer()
      } else {
        this.hideDrawer()
      }
    },
    //添加表情
    addEmoji(em) {
      this.textMsg += em.alt
    },

    //获取焦点，如果不是选表情ing,则关闭抽屉
    textareaFocus() {
      if (this.popupLayerClass == 'showLayer' && this.hideMore == false) {
        this.hideDrawer()
      }
    },
    // 发送文字消息
    sendText() {
      this.hideDrawer() //隐藏抽屉
      if (!this.textMsg) {
        return
      }
      let content = this.replaceEmoji(this.textMsg)
      let msg = {
        text: content,
      }
      this.sendMsg(msg, 'text')
      this.textMsg = '' //清空输入框
    },
    //替换表情符号为图片
    replaceEmoji(str) {
      let replacedStr = str.replace(/\[([^(\]|\[)]*)\]/g, (item, index) => {
        for (let i = 0; i < this.emojiList.length; i++) {
          let row = this.emojiList[i]
          for (let j = 0; j < row.length; j++) {
            let EM = row[j]
            if (EM.alt == item) {
              //在线表情路径，图文混排必须使用网络路径，请上传一份表情到你的服务器后再替换此路径
              //比如你上传服务器后，你的100.gif路径为https://www.xxx.com/emoji/100.gif 则替换onlinePath填写为https://www.xxx.com/emoji/
              let onlinePath = 'https://files.yzsheng.com/bussiness/imgs/emoji/'
              let imgstr = '<img src="' + onlinePath + EM.url + '">'
              return imgstr
            }
          }
        }
      })
      return replacedStr
    },

    // 发送文本消息
    sendMsg(content, type) {
      let message = this.tim.createTextMessage({
        to: this.toUserId,
        conversationType: 'C2C',
        payload: {
          text: content.text,
        },
      })
      this.$store.commit('news/pushCurrentMessageList', message)
      let pomise = this.tim.sendMessage(message)
      pomise
        .then((res) => {
          this.$nextTick(() => {
            // 滚动到底
            this.scrollToView = res.data.message.ID
          })
        })
        .catch((err) => {
          console.log(err)
          uni.showToast({
            title: '发送失败，请稍后重试',
            icon: 'none',
          })
        })

      if (!this.isAddFlow) {
        this.addChatFlow()
      }
    },

    //发送语音消息
    sendRecord(content) {
      let message = this.tim.createCustomMessage({
        to: this.toUserId,
        conversationType: 'C2C',
        // 消息优先级，用于群聊（v2.4.2起支持）。如果某个群的消息超过了频率限制，后台会优先下发高优先级的消息，详细请参考：https://cloud.tencent.com/document/product/269/3663#.E6.B6.88.E6.81.AF.E4.BC.98.E5.85.88.E7.BA.A7.E4.B8.8E.E9.A2.91.E7.8E.87.E6.8E.A7.E5.88.B6)
        // 支持的枚举值：TIM.TYPES.MSG_PRIORITY_HIGH, TIM.TYPES.MSG_PRIORITY_NORMAL（默认）, TIM.TYPES.MSG_PRIORITY_LOW, TIM.TYPES.MSG_PRIORITY_LOWEST
        // priority: TIM.TYPES.MSG_PRIORITY_HIGH,
        payload: {
          data: 'record', // 用于标识该消息类型
          description: content.url, // 用于装载url
          extension: content.times, //录音时长
        },
      })
      this.$store.commit('news/pushCurrentMessageList', message)
      let pomise = this.tim.sendMessage(message)
      pomise
        .then((res) => {
          this.$nextTick(() => {
            // 滚动到底
            this.scrollToView = res.data.message.ID
          })
        })
        .catch((err) => {
          console.log(err + '111')
          uni.showToast({
            title: '发送失败，请稍后重试',
            icon: 'none',
          })
        })

      if (!this.isAddFlow) {
        this.addChatFlow()
      }
    },

    // 添加文字消息到列表
    addTextMsg(msg) {
      this.msgList.push(msg)
    },
    // 添加语音消息到列表
    addVoiceMsg(msg) {
      this.msgList.push(msg)
    },
    // 添加图片消息到列表
    // addImgMsg(msg) {
    //   msg.msg.content = this.setPicSize(msg.msg.content)
    //   this.msgImgList.push(msg.msg.content.url)
    //   this.msgList.push(msg)
    // },
    addRedEnvelopeMsg(msg) {
      this.msgList.push(msg)
    },
    // 添加系统文字消息到列表
    addSystemTextMsg(msg) {
      this.msgList.push(msg)
    },
    // 添加系统红包消息到列表
    addSystemRedEnvelopeMsg(msg) {
      this.msgList.push(msg)
    },
    // 打开红包
    openRedEnvelope(msg, index) {
      let rid = msg.content.rid
      uni.showLoading({
        title: '加载中...',
      })
      //模拟请求服务器效果
      setTimeout(() => {
        //加载数据
        if (rid == 0) {
          this.redenvelopeData = {
            rid: 0, //红包ID
            from: '大黑哥',
            face: '/static/img/im/face/face.jpg',
            blessing: '恭喜发财，大吉大利',
            money: '已领完',
          }
        } else {
          this.redenvelopeData = {
            rid: 1, //红包ID
            from: '售后客服008',
            face: '/static/img/im/face/face_2.jpg',
            blessing: '恭喜发财',
            money: '0.01',
          }
          if (!msg.content.isReceived) {
            // {type:"system",msg:{id:8,type:"redEnvelope",content:{text:"你领取了售后客服008的红包"}}},
            this.sendSystemMsg(
              {
                text:
                  '你领取了' +
                  (msg.userinfo.uid == this.myuid
                    ? '自己'
                    : msg.userinfo.username) +
                  '的红包',
              },
              'redEnvelope'
            )
            this.msgList[index].msg.content.isReceived = true
          }
        }
        uni.hideLoading()
        this.windowsState = 'show'
      }, 200)
    },

    // 关闭红包弹窗
    closeRedEnvelope() {
      this.windowsState = 'hide'
      setTimeout(() => {
        this.windowsState = ''
      }, 200)
    },
    sendSystemMsg(content, type) {
      let lastid = this.msgList[this.msgList.length - 1].msg.id
      lastid++
      let row = {
        type: 'system',
        msg: {
          id: lastid,
          type: type,
          content: content,
        },
      }
      this.screenMsg(row)
    },
    //领取详情
    toDetails(rid) {
      uni.navigateTo({
        url: 'HM-details/HM-details?rid=' + rid,
      })
    },
    // 预览图片
    // showPic(msg) {
    //   uni.previewImage({
    //     indicator: 'none',
    //     current: msg.payload.description,
    //     urls: this.msgImgList
    //   })
    // },
    // 播放语音
    playVoice(msg, id) {
      if (!this.isPlay) {
        this.playMsgid = id
        this.AUDIO.src = msg
        this.isPlay = true
        this.$nextTick(function () {
          this.AUDIO.play()
        })
      } else {
        this.isPlay = false
        this.$nextTick(function () {
          this.AUDIO.stop()
        })
      }
    },
    // 录音开始
    voiceBegin(e) {
      if (e.touches.length > 1) {
        return
      }
      this.initPoint.Y = e.touches[0].clientY
      this.initPoint.identifier = e.touches[0].identifier
      this.RECORDER.start({
        format: 'mp3',
      }) //录音开始,
    },
    //录音开始UI效果
    recordBegin(e) {
      this.recording = true
      this.voiceTis = '松开 结束'
      this.recordLength = 0
      this.recordTimer = setInterval(() => {
        this.recordLength++
      }, 1000)
    },
    // 录音被打断
    voiceCancel() {
      this.recording = false
      this.voiceTis = '按住 说话'
      this.recordTis = '手指上滑 取消发送'
      this.willStop = true //不发送录音
      this.RECORDER.stop() //录音结束
    },
    // 录音中(判断是否触发上滑取消发送)
    voiceIng(e) {
      if (!this.recording) {
        return
      }
      let touche = e.touches[0]
      //上滑一个导航栏的高度触发上滑取消发送
      if (this.initPoint.Y - touche.clientY >= uni.upx2px(100)) {
        this.willStop = true
        this.recordTis = '松开手指 取消发送'
      } else {
        this.willStop = false
        this.recordTis = '手指上滑 取消发送'
      }
    },
    // 结束录音
    voiceEnd(e) {
      if (!this.recording) {
        return
      }
      this.recording = false
      this.voiceTis = '按住 说话'
      this.recordTis = '手指上滑 取消发送'
      this.RECORDER.stop() //录音结束
    },
    //录音结束(回调文件)
    recordEnd(e) {
      clearInterval(this.recordTimer)
      if (!this.willStop) {
        // let msg = {
        //   length: 0,
        //   url: e.tempFilePath
        // }
        // let min = parseInt(this.recordLength / 60)
        // let sec = this.recordLength % 60
        // min = min < 10 ? '0' + min : min
        // sec = sec < 10 ? '0' + sec : sec
        // msg.length = min + ':' + sec
        if (this.recordLength < 2) {
          uni.showToast({
            title: '说话时间太短',
            icon: 'none',
          })
          return
        }
        const _this = this
        this.getFileConfig((params) => {
          uni.uploadFile({
            url: params.host,
            formData: {
              policy: params.policy,
              authorization: params.auth,
            },
            filePath: e.tempFilePath,
            name: 'file',
            success(res) {
              const resObj = JSON.parse(res.data)
              _this.sendRecord({
                url: 'https://ztc.yzsheng.com' + resObj.url,
                times: _this.recordLength + '',
              })
            },
          })
        })
      } else {
        console.log('取消发送录音')
      }
      this.willStop = false
    },
    // 切换语音/文字输入
    switchVoice() {
      this.hideDrawer()
      this.isVoice = this.isVoice ? false : true
    },

    discard() {
      return
    },

    //选取图片
    uploadImage(type) {
      const _this = this
      uni.chooseImage({
        count: 1, // 默认9
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: [type], // 从相册选择
        success(result) {
          _this.getImageConfig((params) => {
            uni.uploadFile({
              url: params.host,
              formData: {
                policy: params.policy,
                authorization: params.auth,
              },
              filePath: result.tempFilePaths[0],
              name: 'file',
              success(res) {
                const resObj = JSON.parse(res.data)
                _this.sendImg('https://ztc.yzsheng.com' + resObj.url)
              },
            })
          })
        },
      })
    },

    sendImg(content) {
      let message = this.tim.createCustomMessage({
        to: this.toUserId,
        conversationType: 'C2C',
        // 消息优先级，用于群聊（v2.4.2起支持）。如果某个群的消息超过了频率限制，后台会优先下发高优先级的消息，详细请参考：https://cloud.tencent.com/document/product/269/3663#.E6.B6.88.E6.81.AF.E4.BC.98.E5.85.88.E7.BA.A7.E4.B8.8E.E9.A2.91.E7.8E.87.E6.8E.A7.E5.88.B6)
        // 支持的枚举值：TIM.TYPES.MSG_PRIORITY_HIGH, TIM.TYPES.MSG_PRIORITY_NORMAL（默认）, TIM.TYPES.MSG_PRIORITY_LOW, TIM.TYPES.MSG_PRIORITY_LOWEST
        // priority: TIM.TYPES.MSG_PRIORITY_HIGH,
        payload: {
          data: 'chatFile', // 用于标识该消息类型
          description: content, // 用于装载url
          extension: '',
        },
      })
      this.$store.commit('news/pushCurrentMessageList', message)
      let pomise = this.tim.sendMessage(message)
      pomise
        .then((res) => {
          this.$nextTick(() => {
            // 滚动到底
            this.scrollToView = res.data.message.ID
          })
        })
        .catch((err) => {
          console.log(err + '111')
          uni.showToast({
            title: '发送失败，请稍后重试',
            icon: 'none',
          })
        })
      this.hideDrawer()

      if (!this.isAddFlow) {
        this.addChatFlow()
      }
    },

    //获取图片上传配置信息
    async getImageConfig(callback) {
      try {
        const res = await this.$api.user.getImageConfig()
        callback(res.data)
      } catch (e) {
        //TODO handle the exception
      }
    },

    //获取文件上传配置信息
    async getFileConfig(callback) {
      try {
        const res = await this.$api.user.getFileConfig({ Suffix: 'mp3' })
        callback(res.data)
      } catch (e) {
        console.log(e)
        //TODO handle the exception
      }
    },

    //图片预览
    previewImage(url) {
      uni.previewImage({
        current: 0,
        urls: [url],
      })
    },

    addChatFlow() {
      this.$api.news
        .addChatFlow({
          channel: 0,
          module: 0,
          active_Store_Id: this.userInfo.userId,
          active_User_Id: this.$store.state.tid,
          passive_Store_Id: this.toUserId,
          passive_User_Id: '',
        })
        .then((res) => {
          this.isAddFlow = true
        })
        .catch((e) => {
          console.log(e)
        })
    },
  },
}
